﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarehouseManagement.BusinessLogic.DTO;
using WarehouseManagement.DataAccess;
using WarehouseManagement.Shared;



namespace WarehouseManagement.BusinessLogic.BC
{
    public class ImportBC : BaseBC
    {
        private UserBC _userBC;
        private MerchandiseBC _merchandiseBC;
        private DataChangedLogBC _dataLogBC;
        private StockBC _stockBC;

        public ImportBC()
            : base()
        {
            _userBC = new UserBC();
            _merchandiseBC = new MerchandiseBC();
            _dataLogBC = new DataChangedLogBC();
            _stockBC = new StockBC();
        }

        public void UpdateImport(ImportDTO dto)
        {
            var entity = Context.Imports.SingleOrDefault(e => e.Id == dto.Id);
            if (entity == null) return;
            entity.ImportReason = dto.ImportReason;
            entity.Notes = dto.Notes;
            SubmitChanges();
        }
        public void AddImport(ImportDTO import, IEnumerable<ImportDetailDTO> details)
        {

            if (!Context.Imports.Any(e => e.ImportNumber == import.ImportNumber))
            {
                var importEntity = Convert(import);
                Context.Imports.InsertOnSubmit(importEntity);
                this.SubmitChanges();
            }
            else
            {
                UpdateImport(import);
            }

            foreach (var item in details)
            {
                item.ImportId = import.Id;
                item.CreatedDate = DateTime.Now;
                item.LastModifiedDate = item.CreatedDate;
                item.CreatedBy = GlobalMemory.CurrentLoginUser;

                var d = Convert(item);

                if (!Context.ImportDetails.Any(e => e.Id == item.Id))
                {
                    Context.ImportDetails.InsertOnSubmit(d);
                    this.SubmitChanges();
                }

                _dataLogBC.SetImportDataChanged(item.MerchandiseId, import.ImportDate.Month, import.ImportDate.Year, true);


                // Tính tồn cuối kỳ tháng hiện tại (Đầu kỳ tháng sau)
                var today = import.ImportDate;
                var stockInfo = _stockBC.GetViewStockInfo(item.MerchandiseId,
                    new DateTime(today.Year, today.Month, 1),
                    new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month)));

                var nextMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1);
                _stockBC.AppendMerchandiseInStock(
                    item.MerchandiseId,
                    nextMonth.Month,
                    nextMonth.Year,
                  stockInfo.EndPeriodQuantity,
                  stockInfo.EndPeriodValue);
                _stockBC.UpdateAllMerchandisesInStockAfterDate(
                    item.MerchandiseId,
                    import.ImportDate.Month,
                    import.ImportDate.Year);


            }

        }

        //private void AddImportItemNotSubmitChanges(ImportViewItem import, IEnumerable<ImportDetailViewItem> details)
        //{

        //    if (!Context.Imports.Any(e => e.ImportNumber == import.ImportNumber))
        //    {
        //        var importEntity = Convert(import);
        //        Context.Imports.InsertOnSubmit(importEntity);
        //        this.SubmitChanges();
        //    }

        //    foreach (var item in details)
        //    {
        //        item.ImportId = import.Id;
        //        item.CreatedDate = DateTime.Now;
        //        item.LastModifiedDate = item.CreatedDate;

        //        var d = Convert(item);

        //        if (!Context.ImportDetails.Any(e => e.Id == item.Id))
        //        {
        //            Context.ImportDetails.InsertOnSubmit(d);
        //            this.SubmitChanges();
        //        }
        //        _merchandiseBC.AppendMerchandiseInStock(item.MerchandiseId, item.CreatedDate,
        //           item.Quantity, (decimal)(item.UnitPriceAfterTax * (decimal)item.Quantity) * item.ExchangeRate);


        //    }






        //    //foreach (var detail in details)
        //    //{

        //    //    detail.Import = import;
        //    //    Context.ImportDetails.InsertOnSubmit(detail);


        //    //    this.SubmitChanges();


        //    //}
        //}

        public void UpdateImportDetail(ImportDetailDTO item)
        {
            var importDetail = Context.ImportDetails.SingleOrDefault(e => e.Id == item.Id);


            //if (item.MerchandiseId == importDetail.MerchandiseId)
            //{
            //    var quantity = item.Quantity - importDetail.Quantity;

            //    var oldValue = (decimal)importDetail.UnitPriceAfterTax * importDetail.Import.ExchangeRate * (decimal)importDetail.Quantity;
            //    var newValue = item.UnitPriceAfterTax * importDetail.Import.ExchangeRate * (decimal)item.Quantity;

            //    _stockBC.AppendMerchandiseInStock(
            //        item.MerchandiseId,
            //        importDetail.Import.ImportDate.Month,
            //        importDetail.Import.ImportDate.Year,
            //        quantity, newValue - oldValue);
            //    _stockBC.UpdateAllMerchandisesInStockAfterDate(
            //        item.MerchandiseId,
            //      importDetail.Import.ImportDate.Month,
            //        importDetail.Import.ImportDate.Year,
            //                quantity, newValue - oldValue);
            //}
            //else
            //{
            //    var quantityToUpdate = importDetail.Quantity * -1;
            //    var valueToUpdate = (decimal)(importDetail.Quantity * importDetail.UnitPriceAfterTax) * importDetail.Import.ExchangeRate * -1;
            //    _stockBC.AppendMerchandiseInStock(
            //        importDetail.MerchandiseId,
            //       importDetail.Import.ImportDate.Month,
            //        importDetail.Import.ImportDate.Year,
            //            importDetail.Quantity * -1,
            //            valueToUpdate);
            //    _stockBC.UpdateAllMerchandisesInStockAfterDate(
            //        importDetail.MerchandiseId,
            //       importDetail.Import.ImportDate.Month,
            //        importDetail.Import.ImportDate.Year,
            //            quantityToUpdate, valueToUpdate);

            //    quantityToUpdate = item.Quantity;
            //    valueToUpdate = (decimal)item.Quantity * item.UnitPriceAfterTax * importDetail.Import.ExchangeRate;
            //    _stockBC.AppendMerchandiseInStock(
            //        item.MerchandiseId,
            //       importDetail.Import.ImportDate.Month,
            //        importDetail.Import.ImportDate.Year,
            //                   quantityToUpdate, valueToUpdate);
            //    _stockBC.UpdateAllMerchandisesInStockAfterDate(
            //        item.MerchandiseId,
            //      importDetail.Import.ImportDate.Month,
            //        importDetail.Import.ImportDate.Year,
            //            quantityToUpdate, valueToUpdate);


            //    // Update data changed log
            //    _dataLogBC.SetImportDataChanged(item.MerchandiseId, importDetail.Import.ImportDate.Month,
            //        importDetail.Import.ImportDate.Year, true);
            //}

            //
            importDetail.LastModifiedDate = DateTime.Now;
            importDetail.OriginPrice = item.OriginPrice;
            importDetail.Quantity = item.Quantity;
            importDetail.ShippingFee = item.ShippingFee;
            importDetail.Tax = item.Tax;
            importDetail.Merchandise = Context.Merchandises.SingleOrDefault(e => e.Id == item.MerchandiseId);
            this.SubmitChanges();

            _dataLogBC.SetImportDataChanged(item.MerchandiseId, importDetail.Import.ImportDate.Month, importDetail.Import.ImportDate.Year, true);


            // Tính tồn cuối kỳ tháng hiện tại (Đầu kỳ tháng sau)
            var today = importDetail.Import.ImportDate;
            var stockInfo = _stockBC.GetViewStockInfo(item.MerchandiseId,
                new DateTime(today.Year, today.Month, 1),
                new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month)));

            var nextMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1);
            _stockBC.AppendMerchandiseInStock(
                item.MerchandiseId,
                nextMonth.Month,
                nextMonth.Year,
              stockInfo.EndPeriodQuantity,
              stockInfo.EndPeriodValue);
            _stockBC.UpdateAllMerchandisesInStockAfterDate(
                item.MerchandiseId,
                importDetail.Import.ImportDate.Month,
                importDetail.Import.ImportDate.Year);



        }

        public void UpdateImportDetails(IEnumerable<ImportDetailDTO> items, ImportDTO master)
        {
            var import = Context.Imports.SingleOrDefault(e => e.ImportNumber == master.ImportNumber);
            if (import != null)
            {
                import.ImportReason = master.ImportReason;
                import.Notes = master.Notes;
                import.Currency = Context.Currencies.SingleOrDefault(e => e.Id == master.CurrencyId);
                import.ExchangeRate = master.ExchangeRate;
            }
            SubmitChanges();

            foreach (var item in items)
            {
                UpdateImportDetail(item);
            }

            UpdateImport(master);
        }

        public void DeleteImportDetail(Guid detailId)
        {
            var item = Context.ImportDetails.SingleOrDefault(e => e.Id == detailId);
            if (item != null)
            {
                //var quantityToUpdate = item.Quantity * -1;
                //var valueToUpdate = (decimal)(item.UnitPriceAfterTax * item.Quantity) * item.Import.ExchangeRate * (-1);
                //_stockBC.AppendMerchandiseInStock(
                //    item.MerchandiseId,
                //    item.Import.ImportDate.Month,
                //    item.Import.ImportDate.Year,
                //   quantityToUpdate, valueToUpdate);
                //_stockBC.UpdateAllMerchandisesInStockAfterDate(
                //    item.MerchandiseId,
                //     item.Import.ImportDate.Month,
                //    item.Import.ImportDate.Year,
                //   quantityToUpdate, valueToUpdate);

                // Update data changed log
                _dataLogBC.SetImportDataChanged(item.MerchandiseId, item.Import.ImportDate.Month,
                    item.Import.ImportDate.Year, true);

                var today = item.Import.ImportDate;
                var merchandiseId = item.MerchandiseId;

                Context.ImportDetails.DeleteOnSubmit(item);
                this.SubmitChanges();



                // Tính tồn cuối kỳ tháng hiện tại (Đầu kỳ tháng sau)

                var stockInfo = _stockBC.GetViewStockInfo(merchandiseId,
                    new DateTime(today.Year, today.Month, 1),
                    new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month)));

                var nextMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1);
                _stockBC.AppendMerchandiseInStock(
                    merchandiseId,
                    nextMonth.Month,
                    nextMonth.Year,
                  stockInfo.EndPeriodQuantity,
                  stockInfo.EndPeriodValue);
                _stockBC.UpdateAllMerchandisesInStockAfterDate(
                    merchandiseId,
                    today.Month,
                    today.Year);

            }
        }

        public void DeleteImportDetails(IEnumerable<Guid> detailIds)
        {
            foreach (var id in detailIds)
            {
                DeleteImportDetail(id);
            }

        }

        private void DeleteImport(Guid importId)
        {
            var import = Context.Imports.SingleOrDefault(e => e.Id == importId);
            if (import != null)
            {
                Context.Imports.DeleteOnSubmit(import);
                SubmitChanges();
            }
        }

        public void SaveImport(ImportDTO masterObj, IEnumerable<ImportDetailDTO> submittedRecords, bool editMode = false)
        {
            try
            {
                this.BeginTransaction();

                var allItems = Context.ImportDetails.Where(e => e.Import.ImportNumber == masterObj.ImportNumber)
                    .Select(e => Convert(e))
                    .ToList();

                var addedItems = GetAddedItems(allItems, submittedRecords).ToList();
                var deletedItems = GetDeletedItems(allItems, submittedRecords).ToList();
                var needUpdatedItems = GetNeedUpdatedItems(addedItems, deletedItems, submittedRecords).ToList();

                if (addedItems.Count > 0)
                {
                    this.AddImport(masterObj, addedItems);
                }
                if (editMode)
                {
                    if (needUpdatedItems.Count > 0)
                    {
                        this.UpdateImportDetails(needUpdatedItems, masterObj);
                    }
                    if (deletedItems.Count > 0)
                    {
                        this.DeleteImportDetails(deletedItems.Select(e => e.Id));
                        var importInDb = Context.Imports.SingleOrDefault(e => e.Id == masterObj.Id);
                        if (importInDb.ImportDetails.Count == 0)
                            DeleteImport(importInDb.Id);
                    }
                }


                this.CommitTransaction();
            }
            catch (Exception ex)
            {
                this.RollbackTransaction();
                throw ex;
            }
        }


        private IEnumerable<ImportDetailDTO> GetDeletedItems(IEnumerable<ImportDetailDTO> allItems, IEnumerable<ImportDetailDTO> submitted)
        {
            var idList = allItems.Select(e => e.Id)
                .Except(submitted.Select(e => e.Id));
            foreach (var id in idList)
            {
                yield return allItems.SingleOrDefault(e => e.Id == id);
            }
        }

        private IEnumerable<ImportDetailDTO> GetAddedItems(IEnumerable<ImportDetailDTO> allItems, IEnumerable<ImportDetailDTO> submitted)
        {
            var idList = submitted.Select(e => e.Id)
                .Except(allItems.Select(e => e.Id));
            foreach (var id in idList)
            {
                yield return submitted.SingleOrDefault(e => e.Id == id);
            }
        }

        private IEnumerable<ImportDetailDTO> GetNeedUpdatedItems(
            IEnumerable<ImportDetailDTO> added,
            IEnumerable<ImportDetailDTO> deleted,
            IEnumerable<ImportDetailDTO> submitted)
        {
            var addedAndDeleted = added.Select(e => e.Id).Union(deleted.Select(e => e.Id));
            var needUpdatedIds = submitted.Select(e => e.Id).Except(addedAndDeleted);
            foreach (var id in needUpdatedIds)
            {
                yield return submitted.SingleOrDefault(e => e.Id == id);
            }
        }

        public void ReturnMerchandiseToStock(Import dto)
        {
            //dto.IsVirtual = true;

        }

        public string GenerateNewImportNumber()
        {
            decimal no = 1;
            var today = DateTime.Now;
            var prefix = "PN";

            var list = Context.Imports.OrderByDescending(e => e.CreatedDate).ToList();
            if (list.Count() > 0)
            {
                var first = list.FirstOrDefault();
                if (first != null)
                {
                    var lastNo = decimal.Parse(first.ImportNumber.Substring(10, 6));
                    if (first.CreatedDate.Month == today.Month && first.CreatedDate.Year == today.Year)
                        no = lastNo + 1;

                }
            }

            var newNumber = NumberGenerator.GenerateNumber(prefix, today.Month, today.Year, no);
            return newNumber;

        }


        public ImportDTO GetImportByNumber(string number)
        {
            var obj = (Context.Imports.SingleOrDefault(e => e.ImportNumber == number));
            if (obj != null) return Convert(obj);
            return null;
        }


        public void ExcludeImportItem(Guid importId, int merchandiseId, double quantity, decimal itemPrice, string notes)
        {
            try
            {
                //_imRepo.BeginTransaction();

                //var dto = new ExportDTO()
                //{
                //    Id = Guid.NewGuid(),
                //    CreatedBy = GlobalMemory.CurrentLoginUser,
                //    Merchandise = new DTO.Merchandise.MerchandiseDTO() { Id = merchandiseId },
                //    CustomerId = null,
                //    ExportDate = DateTime.Now,
                //    ExportPrice = itemPrice,
                //    IsCancelled = true,
                //    Quantity = quantity,
                //    Notes = notes,
                //    OriginalPrice = itemPrice

                //};
                //ExportWithoutCommitTransaction(dto, itemPrice);


                ////_imRepo.SetImportItemIsVirtual(importId);
                ////_imRepo.SubmitChanges();
                ////// Update Average Import Price for all items >= that day

                ////var avgPriceTimeList = _merRepo.GetAverageImportUnitPriceTimeList(dto.ExportDate.Date, merchandiseId).ToList();
                ////foreach (var t in avgPriceTimeList)
                ////{
                ////    var updatedAvgImportUnitPrice = _imRepo.ComputeAverageImportUnitPriceFrom(t.Date, merchandiseId);
                ////    _imRepo.RecordAverageUnitPrice(t, merchandiseId, updatedAvgImportUnitPrice);
                ////}
                ////_imRepo.SubmitChanges();
                //_imRepo.CommitTransaction();
            }
            catch (Exception ex)
            {
                //_imRepo.RollbackTransaction();
                throw ex;
            }
        }



        private dynamic GetImportInformation(int merchandiseId, DateTime from, DateTime to)
        {
            var list = Context.ImportDetails.Where(e =>
                        e.MerchandiseId == merchandiseId &&
                       (e.Import.ImportDate.Date >= from.Date && e.Import.ImportDate.Date <= to.Date));

            dynamic result = new { TotalImportQuantity = 0, TotalImportValue = 0 };
            if (list.Count() > 0)
            {
                var qty = list.Sum(e => e.Quantity);
                var value = list.Sum(e => (decimal)((double)e.UnitPriceAfterTax * e.Quantity) * e.Import.ExchangeRate);
                result = new { TotalImportQuantity = qty, TotalImportValue = value };
            }
            return result;
        }

        public dynamic GetImportInformationOptimized(int merchandiseId, DateTime from, DateTime to)
        {
            double qty = 0;
            decimal value = 0;




            DateTime t = from.Date;
            while (t <= to.Date)
            {
                if (t == new DateTime(t.Year, t.Month, 1) && t.AddDays(DateTime.DaysInMonth(t.Year, t.Month) - 1) <= to.Date)
                {
                    EnsureMonthlyImportData(merchandiseId, t.Month, t.Year);

                    var obj = GetImportExportInformationByMonth(merchandiseId, t.Month, t.Year);
                    if (obj != null)
                    {
                        qty += obj.ImportQuantity;
                        value += obj.ImportValue;
                    }

                    t = t.AddMonths(1);
                }
                else
                {
                    var toDate = new DateTime(t.Year, t.Month, DateTime.DaysInMonth(t.Year, t.Month));
                    if (toDate > to.Date)
                        toDate = to.Date;

                    var obj = GetImportInformation(merchandiseId, t.Date, toDate);
                    qty += obj.TotalImportQuantity;
                    value += obj.TotalImportValue;

                    t = toDate.AddDays(1);
                }


            }


            return new { TotalImportValue = value, TotalImportQuantity = qty };
        }


        private void EnsureMonthlyImportData(int merchandiseId, int month, int year)
        {

            if (_dataLogBC.IsImportDataChanged(merchandiseId, month, year))
            {
                var updatedImportInfo = GetImportInformation(merchandiseId, new DateTime(year, month, 1),
                     new DateTime(year, month, DateTime.DaysInMonth(year, month)));
                UpdateMonthlyImportExport(merchandiseId, month, year,
                    updatedImportInfo.TotalImportQuantity, updatedImportInfo.TotalImportValue);
                _dataLogBC.SetImportDataChanged(merchandiseId, month, year, false);

            }

        }

        public void UpdateMonthlyImportExport(int merchandiseId, int month, int year,
            double? importQty = null, decimal? importValue = null,
            double? exportQty = null, decimal? exportValue = null, decimal? profit = null)
        {
            var obj = Context.MonthlyImportExports.SingleOrDefault(e => e.MerchandiseId == merchandiseId && e.Month == month && e.Year == year);
            if (obj == null)
            {
                obj = new MonthlyImportExport()
                {
                    Id = Guid.NewGuid(),
                    Year = year,
                    Month = month,
                    MerchandiseId = merchandiseId,
                    ImportValue = importValue.HasValue ? importValue.Value : 0,
                    ImportQuantity = importQty.HasValue ? importQty.Value : 0,
                    ExportValue = exportValue.HasValue ? exportValue.Value : 0,
                    ExportQuantity = exportQty.HasValue ? exportQty.Value : 0,
                    Profit = profit.HasValue ? profit.Value : 0,
                };
                Context.MonthlyImportExports.InsertOnSubmit(obj);
            }
            else
            {
                if (importQty.HasValue)
                    obj.ImportQuantity = importQty.Value;
                if (importValue.HasValue)
                    obj.ImportValue = importValue.Value;

                if (exportQty.HasValue)
                {
                    obj.ExportQuantity = exportQty.Value;
                }

                if (exportValue.HasValue)
                    obj.ExportValue = exportValue.Value;

                if (profit.HasValue)
                    obj.Profit = profit.Value;
            }
            SubmitChanges();
        }
        public MonthlyImportExport GetImportExportInformationByMonth(int merchandiseId, int month, int year)
        {
            var item = Context.MonthlyImportExports.SingleOrDefault(e => e.MerchandiseId == merchandiseId
                && e.Month == month && e.Year == year);
            if (item != null)
                return item;
            return new MonthlyImportExport() { MerchandiseId = merchandiseId, Month = month, Year = year };
        }
        //private MonthlyImportExport GetImportExportInformationByMonth(int merchandiseId, int fromMonth, int fromYear, int toMonth, int toYear)
        //{
        //    var list = Context.MonthlyImportExports
        //        .AsEnumerable()
        //        .Where(e => (new DateTime(e.Year, e.Month, 1).Date >= new DateTime(fromYear, fromMonth, 1).Date
        //            && new DateTime(e.Year, e.Month, 1).Date < new DateTime(toYear, toMonth, 1).Date)
        //            && e.MerchandiseId == merchandiseId);
        //    if (list.Count() > 0)
        //    {
        //        var importQty = list.Sum(e => e.ImportQuantity);
        //        var importValue = list.Sum(e => e.ImportValue);
        //        var exportQty = list.Sum(e => e.ExportQuantity);
        //        var exportValue = list.Sum(e => e.ExportValue);
        //        var profit = list.Sum(e => e.Profit);
        //        return new MonthlyImportExport()
        //        {
        //            Profit = profit,
        //            ExportQuantity = exportQty,
        //            ExportValue = exportValue,
        //            ImportValue = importValue,
        //            ImportQuantity = importQty,
        //            MerchandiseId = merchandiseId,
        //        };
        //    }
        //    return new MonthlyImportExport();
        //}

        public IEnumerable<ImportDetailDTO> GetImportList(DateTime from, DateTime to)
        {
            return GetImportDetailEntityList(from, to)
                .Select(e => Convert(e))
                .AsEnumerable();
        }

        public IEnumerable<ImportDetailDTO> GetImportList(string importNumber, int merchandiseId)
        {
            return Context.ImportDetails.Where(e => e.MerchandiseId == merchandiseId
                && e.Import.ImportNumber == importNumber)
                .Select(e => Convert(e));
        }

        public IEnumerable<ImportDetailDTO> GetImportList(string importNumber)
        {
            return Context.ImportDetails.Where(e =>
               e.Import.ImportNumber == importNumber)
               .Select(e => Convert(e));
        }

        private IEnumerable<ImportDetail> GetImportDetailEntityList(DateTime from, DateTime to)
        {
            return Context.ImportDetails.Where(e => e.Import.ImportDate.Date >= from.Date
                           && e.Import.ImportDate.Date <= to.Date);

        }

        public IEnumerable<ViewImportDetailDTO> GetImportSummaryList(DateTime from, DateTime to)
        {
            var list = GetImportDetailEntityList(from, to);
            var summary = from p in list
                          //let k = new
                          //{
                          //    ImportDate = p.Import.ImportDate,
                          //    ImportId = p.Import.Id,
                          //    ImportNumber = p.Import.ImportNumber,
                          //    MerchandiseId = p.MerchandiseId,
                          //    MerchandiseName = p.Merchandise.MerchandiseName,
                          //    Unit = p.Merchandise.Unit,
                          //    OriginUnitPrice = p.OriginPrice,
                          //    Tax = p.Tax,
                          //    ShippingFee = p.ShippingFee,
                          //    UnitPriceAfterTax = p.UnitPriceAfterTax,
                          //    ExchangeRate = p.ExchangeRate,
                          //    CurrencyName = p.Currency.CurrencyName
                          //}
                          //group p by k into t
                          select new ViewImportDetailDTO()
                          {
                              ImportId = p.ImportId,
                              ImportNumber = p.Import.ImportNumber,
                              DocumentNumber = p.Import.DocumentNumber,
                              CurrencyId = p.Import.CurrencyId,
                              ImportDate = p.Import.ImportDate,
                              MerchandiseId = p.MerchandiseId,
                              MerchandiseName = p.Merchandise.MerchandiseName,
                              MerchandiseCategory = p.Merchandise.MerchandiseCategory.MerchandiseCategoryName,
                              Unit = p.Merchandise.Unit,
                              OriginUnitPrice = p.OriginPrice,
                              Tax = p.Tax,
                              ShippingFee = p.ShippingFee,
                              UnitPriceAfterTax = (decimal)p.UnitPriceAfterTax,
                              ExchangeRate = p.Import.ExchangeRate,
                              CurrencyName = p.Import.Currency.CurrencyName,
                              Quantity = p.Quantity,
                              TotalUnitPrice = (decimal)p.UnitPriceAfterTax * p.Import.ExchangeRate * (decimal)p.Quantity

                          };
            return summary.ToList();

        }


        public decimal GetTotalImportValueInDay(DateTime date, int? merchandiseId = null)
        {
            var list = Context.ImportDetails.Where(e => e.Import.ImportDate.Date == date.Date);
            if (merchandiseId.HasValue)
            {
                list = list.Where(e => e.MerchandiseId == merchandiseId.Value);
            }
            if (list.Count() > 0)
                return list.Sum(e => (decimal)e.UnitPriceAfterTax * (decimal)e.Quantity * e.Import.ExchangeRate);
            return 0;
        }

        private ImportDetail Convert(ImportDetailDTO viewItem)
        {
            return new ImportDetail()
            {

                Id = viewItem.Id,

                CreatedDate = viewItem.CreatedDate,
                LastModifiedDate = viewItem.LastModifiedDate,
                CreatedBy = viewItem.CreatedBy,
                Tax = viewItem.Tax,
                ShippingFee = viewItem.ShippingFee,
                Quantity = viewItem.Quantity,
                OriginPrice = viewItem.OriginPrice,
                //ExchangeRate = viewItem.ExchangeRate,
                //CurrencyId = viewItem.CurrencyId,
                ImportId = viewItem.ImportId,
                MerchandiseId = viewItem.MerchandiseId,
                UnitPriceAfterTax = (double)viewItem.UnitPriceAfterTax,

            };
        }

        private ImportDetailDTO Convert(ImportDetail viewItem)
        {
            return new ImportDetailDTO()
            {
                Id = viewItem.Id,

                CreatedDate = DateTime.Now,
                LastModifiedDate = DateTime.Now,
                CreatedBy = GlobalMemory.CurrentLoginUser,
                Tax = viewItem.Tax,
                ShippingFee = viewItem.ShippingFee,
                Quantity = viewItem.Quantity,
                OriginPrice = viewItem.OriginPrice,
                ExchangeRate = viewItem.Import.ExchangeRate,
                //CurrencyId = viewItem.Import.CurrencyId,
                ImportId = viewItem.ImportId,
                MerchandiseId = viewItem.MerchandiseId,
                MerchandiseUnit = viewItem.Merchandise.Unit,


            };
        }

        private Import Convert(ImportDTO viewItem)
        {
            return new Import()
            {
                Id = viewItem.Id,
                ImportNumber = viewItem.ImportNumber,
                ImportDate = viewItem.ImportDate,
                Notes = viewItem.Notes,
                ImportReason = viewItem.ImportReason,
                CreatedDate = viewItem.CreatedDate,
                CurrencyId = viewItem.CurrencyId,
                ExchangeRate = viewItem.ExchangeRate,
                SupplierId = viewItem.SupplierId,
                DocumentNumber = viewItem.DocumentNumber
            };
        }

        private ImportDTO Convert(Import entity)
        {
            return new ImportDTO()
            {
                Id = entity.Id,
                ImportNumber = entity.ImportNumber,
                ImportDate = entity.ImportDate,
                Notes = entity.Notes,
                ImportReason = entity.ImportReason,
                CreatedDate = entity.CreatedDate,
                CurrencyId = entity.CurrencyId,
                ExchangeRate = entity.ExchangeRate,
                SupplierId = entity.SupplierId,
                DocumentNumber = entity.DocumentNumber
            };
        }


    }
}
